//
//  ADJgSDKSplashAdapter.m
//  AnyThinkSDKDemo
//
//  Created by 刘娟 on 2024/9/25.
//  Copyright © 2024 抽筋的灯. All rights reserved.
//

#import "ADJgSDKSplashAdapter.h"
#import "ADJgSDKSplashCustomEvent.h"
#import "ATADJgSDKBiddingRequest.h"
#import "ATADJgSDKBiddingManager.h"
#import "ADJgSDKSplashAdContainer.h"

@interface ADJgSDKSplashAdapter ()
@property (nonatomic, strong) ADJgSDKSplashCustomEvent *customEvent;
@property (nonatomic, strong) ADJgSDKSplashAdContainer *splashAdContainer;
@end

@implementation ADJgSDKSplashAdapter

-(instancetype) initWithNetworkCustomInfo:(NSDictionary*)serverInfo localInfo:(NSDictionary*)localInfo {
    self = [super init];
    if (self != nil) {
        if (![[ATAPI sharedInstance] initFlagForNetwork:@"ADJgSDK"]) {
            [[ATAPI sharedInstance] setInitFlagForNetwork:@"ADJgSDK"];
            [ADJgSDK initWithAppId:serverInfo[@"app_id"] completionBlock:^(NSError * _Nullable error) {
                if (error){
                    [[ATAPI sharedInstance] setInitFlag:0 forNetwork:@"ADJgSDK"];
                    NSLog(@"ADJgSDK 初始化失败%@",error);
                }
            }];
        }
       
    }
    return self;
}

- (void)loadADWithInfo:(NSDictionary*)serverInfo localInfo:(NSDictionary*)localInfo completion:(void (^)(NSArray<NSDictionary *> *, NSError *))completion {
    
    NSTimeInterval tolerateTimeout = localInfo[kATSplashExtraTolerateTimeoutKey] ? [localInfo[kATSplashExtraTolerateTimeoutKey] doubleValue] : 5.0;
    if (tolerateTimeout > 0) {
        _customEvent = [[ADJgSDKSplashCustomEvent alloc] initWithInfo:serverInfo localInfo:localInfo];
        _customEvent.requestCompletionBlock = completion;
//        _customEvent.delegate = self.delegateToBePassed;
        
       
        NSString *bidId = serverInfo[kATAdapterCustomInfoBuyeruIdKey];
        if (bidId.length) {
            
            ATADJgSDKBiddingRequest *request = [[ATADJgSDKBiddingManager sharedInstance] getRequestItemWithUnitID:serverInfo[@"slot_id"]];
            
            if (request.customObject!=nil) { // load secced
                self.splashAdContainer = request.customObject;
                self.splashAdContainer.delegate = _customEvent;
                _customEvent.splashAdContainer = self.splashAdContainer;
                [_customEvent trackSplashAdLoaded:self.splashAdContainer];
            } else { // fail
//                NSError *error = [NSError errorWithDomain:ATADLoadingErrorDomain code:ATADLoadingErrorCodeThirdPartySDKNotImportedProperly userInfo:@{NSLocalizedDescriptionKey:@"AT has failed to load splash.", NSLocalizedFailureReasonErrorKey:@"It took too long to load placement stragety."}];
                [_customEvent trackSplashAdLoadFailed:nil];
            }
            [[ATADJgSDKBiddingManager sharedInstance] removeRequestItmeWithUnitID:serverInfo[@"slot_id"]];
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                UIView *bottomView = localInfo[kATSplashExtraContainerViewKey];
                [self->_customEvent loadAdWithPosId:serverInfo[@"slot_id"] bottomView:bottomView];
            });
        }
    } else {
        completion(nil, [NSError errorWithDomain:ATADLoadingErrorDomain code:-100001 userInfo:@{NSLocalizedDescriptionKey:@"AT has failed to load splash.", NSLocalizedFailureReasonErrorKey:@"It took too long to load placement stragety."}]);
    }
}

//v 5.7.06 及以上版本中， splash 广告的 load 和 show 方法已经分开了
+ (void)showSplash:(ATSplash *)splash localInfo:(NSDictionary*)localInfo delegate:(id<ATSplashDelegate>)delegate {
    ADJgSDKSplashAdContainer *splashAdContainer = splash.customObject;
    if (splashAdContainer) {
        UIWindow *window = localInfo[kATSplashExtraWindowKey];
        [splashAdContainer showAdInWindow:window];
    }
}

+(BOOL)adReadyWithCustomObject:(id)customObject info:(NSDictionary*)info{
    ADJgSDKSplashAdContainer *splashAdContainer = customObject;
    return splashAdContainer?YES:NO;
}

#pragma mark - Header bidding
#pragma mark - c2s
+(void)bidRequestWithPlacementModel:(ATPlacementModel*)placementModel unitGroupModel:(ATUnitGroupModel*)unitGroupModel info:(NSDictionary*)info completion:(void(^)(ATBidInfo *bidInfo, NSError *error))completion {

    NSLog(@"%s", __FUNCTION__);
    if (NSClassFromString(@"ADJgSDK") == nil) {
        if (completion != nil) { completion( nil, [NSError errorWithDomain:@"com.ubix.mediation.ios" code:1 userInfo:@{NSLocalizedDescriptionKey:@"Bid request has failed", NSLocalizedFailureReasonErrorKey:@"ADJgSDK is not imported"}]); }
        return;
    }
    
    if (![[ATAPI sharedInstance] initFlagForNetwork:@"ADJgSDK"]) {
        [[ATAPI sharedInstance] setInitFlagForNetwork:@"ADJgSDK"];
        [ADJgSDK initWithAppId:info[@"app_id"] completionBlock:^(NSError * _Nullable error) {
            if (error){
                [[ATAPI sharedInstance] setInitFlag:0 forNetwork:@"ADJgSDK"];
                NSLog(@"ADJgSDK 初始化失败%@",error);
            }else{
                ATADJgSDKBiddingManager *biddingManage = [ATADJgSDKBiddingManager sharedInstance];
                ATADJgSDKBiddingRequest *request = [ATADJgSDKBiddingRequest new];
                request.unitGroup = unitGroupModel;
                request.placementID = placementModel.placementID;
                request.bidCompletion = completion;
                request.unitID = info[@"slot_id"];
                request.extraInfo = info;
                request.adType = ESCAdFormatSplash;
                ADJgSDKSplashAdContainer *splashAdContainer = [[ADJgSDKSplashAdContainer alloc] initPosId:info[@"slot_id"] delegate:nil];
                request.customObject = splashAdContainer;
                [biddingManage startWithRequestItem:request];
                UIView *bottomView = info[kATSplashExtraContainerViewKey];
                [splashAdContainer loadAdWithBottomView:bottomView];
            }
        }];
    }else{
        ATADJgSDKBiddingManager *biddingManage = [ATADJgSDKBiddingManager sharedInstance];
        ATADJgSDKBiddingRequest *request = [ATADJgSDKBiddingRequest new];
        request.unitGroup = unitGroupModel;
        request.placementID = placementModel.placementID;
        request.bidCompletion = completion;
        request.unitID = info[@"slot_id"];
        request.extraInfo = info;
        request.adType = ESCAdFormatSplash;
        ADJgSDKSplashAdContainer *splashAdContainer = [[ADJgSDKSplashAdContainer alloc] initPosId:info[@"slot_id"] delegate:nil];
        request.customObject = splashAdContainer;
        [biddingManage startWithRequestItem:request];
        UIView *bottomView = info[kATSplashExtraContainerViewKey];
        [splashAdContainer loadAdWithBottomView:bottomView];
    }
}

+ (void) sendWinnerNotifyWithCustomObject:(id)customObject secondPrice:(NSString*)price userInfo:(NSDictionary<NSString *, NSString *> *)userInfo {
    NSLog(@"%s", __FUNCTION__);
    ADJgSDKSplashAdContainer *splashAdContainer = (ADJgSDKSplashAdContainer *)customObject;
#if DEBUG
    NSLog(@"ADJgSDK=============开屏-上报竞赢价格：%ld",[splashAdContainer getBidPrice]);
#endif
}

+ (void)sendLossNotifyWithCustomObject:(nonnull id)customObject lossType:(ATBiddingLossType)lossType winPrice:(nonnull NSString *)price userInfo:(NSDictionary *)userInfo {
    NSLog(@"%s", __FUNCTION__);
    //美元转人民币，转换为分
    CGFloat cnyPrice = price.floatValue * 6.3 * 100;
    ADJgSDKSplashAdContainer *splashAdContainer = (ADJgSDKSplashAdContainer *)customObject;
    
#if DEBUG
    NSLog(@"ADJgSDK=============开屏-上报竞败；竞赢价格：%ld",@(cnyPrice).integerValue);
#endif
}

/*
 说明：
 将ADJgSDK 以自定义适配器方式接入topon
 平台已经配置了适配器和广告位。
 1.当广告位没有开启头部竞价功能，ESCAdmobileSplashAdapter 会走初始化方法-(instancetype) initWithNetworkCustomInfo:(NSDictionary*)serverInfo localInfo:(NSDictionary*)localInfo
 和 - (void)loadADWithInfo:(NSDictionary*)serverInfo localInfo:(NSDictionary*)localInfo completion:(void (^)(NSArray<NSDictionary *> *, NSError *))completion 加载广告，三方广告回调也能正常加载展示。
 2.将topon 广告源开启head bidding 功能后 适配器触发+(void)bidRequestWithPlacementModel:(ATPlacementModel*)placementModel unitGroupModel:(ATUnitGroupModel*)unitGroupModel info:(NSDictionary*)info completion:(void(^)(ATBidInfo *bidInfo, NSError *error))completion 方法。上面初始化和加载广告的就不走了。
 
3.自定义适配器的 head bidding 逻辑按文档描述大致对接如上，广告加载触发不了。因文档介绍不详，麻烦看下还有哪些需要补充的逻辑
 
 */

@end
